package com.zbkj.service.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.zbkj.dal.base.enums.BizTypeEnum;
import com.zbkj.dal.entity.ba.BizImg;
import com.zbkj.dal.entity.ba.Maintain;
import com.zbkj.dal.pojo.request.PageParamRequest;
import com.zbkj.dal.pojo.request.ba.ConcludeMaintainRequest;
import com.zbkj.dal.pojo.request.ba.MaintainQueryRequest;
import com.zbkj.dal.pojo.request.ba.MaintainRequest;
import com.zbkj.dal.pojo.response.ba.MaintainDetailResponse;
import com.zbkj.dal.pojo.response.ba.MaintainResponse;
import com.zbkj.dal.pojo.response.ba.MyMaintainResponse;
import com.zbkj.dal.dao.MaintainMapper;
import com.zbkj.service.service.*;
import com.zbkj.service.util.UserUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 维修保养 服务实现类
 * </p>
 *
 * @author jhui
 * @since 2023-10-03
 */
@Service
public class MaintainServiceImpl extends ServiceImpl<MaintainMapper, Maintain> implements MaintainService {
    @Autowired
    private UserService userService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private BizImgService bizImgService;
    @Autowired
    private SystemAttachmentService systemAttachmentService;
    @Autowired
    private SystemAdminService systemAdminService;
    @Resource
    private AliSmsServiceImpl aliSmsService;

    @Override
    public List<MyMaintainResponse> listMyMaintain(Integer status, PageParamRequest pageParamRequest) {
        List<MyMaintainResponse> result = Lists.newArrayList();
        Integer userId = userService.getUserIdException();
        LambdaQueryWrapper<Maintain> queryWrapper = Wrappers.lambdaQuery(Maintain.class);
        queryWrapper.eq(Maintain::getUid, userId);
        if (status != null && status != -1) {
            queryWrapper.eq(Maintain::getStatus, status);
        }
        queryWrapper.orderByDesc(Maintain::getId);
        queryWrapper.last("LIMIT " + (pageParamRequest.getPage() - 1) * pageParamRequest.getLimit() + "," + pageParamRequest.getLimit());
        List<Maintain> list = list(queryWrapper);

        if (CollUtil.isEmpty(list)) {
            return result;
        }
        List<BizImg> bizImgs = Lists.newArrayList();
        List<Integer> ids = list.stream().map(m -> m.getId()).distinct().collect(Collectors.toList());
        if (CollUtil.isNotEmpty(ids)) {
            bizImgs = bizImgService.listByBizIds(BizTypeEnum.MAINTAIN.getType(), ids);
        }
        for (Maintain share : list) {
            MyMaintainResponse myShareResponse = new MyMaintainResponse();
            BeanUtils.copyProperties(share, myShareResponse);
            List<String> paths = bizImgs.stream().filter(p -> ObjectUtils.nullSafeEquals(p.getBizId(), share.getId())
                            && StringUtils.isNotBlank(p.getPath())).map(m -> m.getPath())
                    .collect(Collectors.toList());
            myShareResponse.setPics(paths);
            result.add(myShareResponse);
        }

        return result;
    }

    @Override
    public Boolean deleteMyMaintain(Integer id) {
        Integer userId = userService.getUserIdException();
        LambdaQueryWrapper<Maintain> queryWrapper = Wrappers.lambdaQuery(Maintain.class);
        queryWrapper.eq(Maintain::getId, id).eq(Maintain::getStatus, 0).eq(Maintain::getUid, userId);
        return this.remove(queryWrapper);
    }

    @Override
    public Boolean create(MaintainRequest maintainRequest) {
        Integer userId = userService.getUserIdException();
        Maintain maintain = new Maintain();
        BeanUtils.copyProperties(maintainRequest, maintain);
        maintain.setUid(userId);
        maintain.setStatus(0);
        maintain.setCreateTime(LocalDateTime.now());
        maintain.setUpdateTime(LocalDateTime.now());

        //            bizImgService.deleteByBizId(BizTypeEnum.SHARE.getType(),)

        return Boolean.TRUE.equals(transactionTemplate.execute((e) -> {
//            bizImgService.deleteByBizId(BizTypeEnum.SHARE.getType(),)
            save(maintain);
            if (CollUtil.isNotEmpty(maintainRequest.getPics())) {
                maintainRequest.getPics().forEach(c -> {
                    c.setBizId(maintain.getId());
                    c.setCreateTime(LocalDateTime.now());
                    c.setUpdateTime(LocalDateTime.now());
                    c.setType(BizTypeEnum.MAINTAIN.getType());
                    c.setPath(systemAttachmentService.clearPrefix(c.getPath()));
                });

                bizImgService.saveBatch(maintainRequest.getPics());

                //发送短息
                aliSmsService.sendServiceMsg("维修保养");
            }
            return Boolean.TRUE;
        }));
    }

    @Override
    public PageInfo<MaintainResponse> queryMaintainPaged(MaintainQueryRequest maintainQueryRequest, PageParamRequest pageParamRequest) {
        LambdaQueryWrapper<Maintain> queryWrapper = Wrappers.lambdaQuery(Maintain.class);
        if (maintainQueryRequest.getStatus() != null) {
            queryWrapper.eq(Maintain::getStatus, maintainQueryRequest.getStatus());
        }
        if (maintainQueryRequest.getBeginDate() != null) {
            queryWrapper.ge(Maintain::getCreateTime, maintainQueryRequest.getBeginDate());
        }
        if (maintainQueryRequest.getEndDate() != null) {
            queryWrapper.lt(Maintain::getCreateTime, maintainQueryRequest.getEndDate().plusDays(1));
        }
        queryWrapper.orderByDesc(Maintain::getId);
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<Maintain> list = this.list(queryWrapper);
        PageInfo<Maintain> pageInfo = PageInfo.of(list);

        PageInfo<MaintainResponse> result = new PageInfo<>();
        result.setTotal(pageInfo.getTotal());
        List<MaintainResponse> dtos = Lists.newArrayList();
        for (Maintain share : pageInfo.getList()) {
            MaintainResponse shareResponse = new MaintainResponse();
            BeanUtils.copyProperties(share, shareResponse);
            dtos.add(shareResponse);
        }
        result.setList(dtos);
        UserUtils.fillUsers(dtos);


        if (CollectionUtils.isNotEmpty(dtos)) {
            List<Integer> adminIds = dtos.stream().filter(p -> p.getOperatorId() != null).distinct().map(m -> m.getOperatorId()).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(adminIds)) {
                Map<Integer, String> nameMapByIdList = systemAdminService.getNameMapByIdList(adminIds);
                for (MaintainResponse maintainResponse : result.getList()) {
                    if (maintainResponse.getOperatorId() == null) {
                        continue;
                    }
                    maintainResponse.setOperatorName(nameMapByIdList.get(maintainResponse.getOperatorId()));
                }
            }
        }

        return result;
    }

    @Override
    public boolean conclude(ConcludeMaintainRequest concludeMaintainRequest) {
        LambdaUpdateWrapper<Maintain> updateWrapper = Wrappers.lambdaUpdate(Maintain.class);
        updateWrapper.set(Maintain::getCode, concludeMaintainRequest.getCode())
                .set(Maintain::getEstimatePrice, concludeMaintainRequest.getEstimatePrice())
                .set(Maintain::getStatus, concludeMaintainRequest.getStatus())
                .set(Maintain::getRemark, concludeMaintainRequest.getRemark())
                .set(Maintain::getOperatorId, concludeMaintainRequest.getOperatorId())
                .set(Maintain::getUpdateTime, LocalDateTime.now())
                .set(Maintain::getServiceFee, concludeMaintainRequest.getServiceFee())
                .eq(Maintain::getId, concludeMaintainRequest.getId());
        boolean result = this.update(updateWrapper);
        return result;
    }

    @Override
    public MaintainDetailResponse detail(Integer id) {
        Maintain maintain = this.getById(id);
        MaintainDetailResponse maintainDetailResponse = new MaintainDetailResponse();
        BeanUtils.copyProperties(maintain, maintainDetailResponse);

        List<BizImg> bizImgs = bizImgService.listByBizId(BizTypeEnum.MAINTAIN.getType(), id);
        maintainDetailResponse.setPics(bizImgs);
        return maintainDetailResponse;
    }
}
